const app = getApp();
var picRoot = app.data.picRoot;
var util = require('../../utils/util.js');
var url = app.data.url;
import Dialog from '/@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    envPic: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    activeNames: ['2'],
    addr: '',
    businessTime: '营业时间:每天8点 ~ 每天17点',
    serviceContent: 'aaasssss',
    lat: '',
    lot: '',
    merchantId: '',
    phone: '0766-2899668',
    unitList: [],
    stepperValue: 0,
    totalPrice: 0,
    name: '',
    descType: '',
    show: false,
    dateValue: '',
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    list14:[]
  },
  onInput: function(event) {
    this.setData({
      currentDate: event.detail
    });
  },
  onConfirm: function(options) {
    let timeStamp = options.detail;
    // 格式化
    let preTime = util.formatDate2(timeStamp);
    let _that = this;
    _that.setData({
      dateValue: preTime,
      show: false
    })
  },
  showPopup: function() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },

  onChange(event) {
    this.setData({
      activeNames: event.detail
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options);
    let _that = this;
    let merchantId = options.merchantId;
    let descType = options.descType;
    _that.setData({
      merchantId: merchantId,
      descType: descType
    })
    wx.request({
      url: url + '/ScenicSystemApi/queryScenicById',
      data: {
        merchantId: merchantId
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 200) {
          let item = res.data.data;
          console.log(item);
          wx.setNavigationBarTitle({
            title: item.merchantName
          })
          let env = item.img;
          let tempEvnList = [];
          if (env != null && env != '') {
            let envArr = env.split(",");
            for (var i = 0; i < envArr.length; i++) {
              tempEvnList.push(picRoot + envArr[i]);
            }
          }

          _that.setData({
            merchantId: merchantId,
            addr: item.address,
            lat: item.lat,
            lot: item.lot,
            name: item.merchantName,
            phone: item.phone,
            list14: item.list13,
            envPic: tempEvnList
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })
    wx.request({
      url: url + '/OilSystemApi/listPageOilPrice',
      data: {
        merchantId: merchantId,
        descType: descType
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data.data);
        if (res.data.code == 200) {
          _that.setData({
            unitList: res.data.data
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  toShowDatePage: function() {

  },
  /**
   * 提交订单
   */
  onSubmit: function(options) {
    let _that = this;
    let cart = _that.data.arr;
    let jsonItem = JSON.stringify(cart);
    let merchantId = _that.data.merchantId;
    let createUserName = app.globalData.openId;
    let queryType = _that.data.queryType;
    let dateValue = _that.data.dateValue;
    let totalPrice = _that.data.totalPrice;
    wx.request({
      url: url + '/OrderApi/insertOrderForScenic',
      data: {
        itemApi: jsonItem,
        merchantId: merchantId,
        token: createUserName,
        queryType: queryType,
        dateValue: dateValue,
        totalPrice: totalPrice
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        const orderId = res.data.data;
        if (res.data.code == 200) {
          wx.reLaunch({
            url: '../../pages/order-detail/index?orderId=' + orderId + "&queryType=" + queryType,
          })
        } else if (res.data.code == 500) {
          // 尚未登录
          Dialog.confirm({
            title: '提示',
            message: '您当前尚未登录, 请点击确认跳转登录页面!'
          }).then(() => {
            // on confirm
            wx.navigateTo({
              url: "../../pages/login/index"
            })
          }).catch(() => {
            // on cancel
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }

    })
  },



  /**
   * 点击步长按钮
   */
  addOrDelStepper: function(options) {
    let _that = this;
    let cart = _that.data.arr;
    let id = options.currentTarget.dataset.id;
    let price = options.currentTarget.dataset.price;
    let tempPrice = 0;
    for (var i = 0; i < cart.length; i++) {
      if (id == cart[i].id) {
        cart[i].num = _that.data.stepperValue;
      }
    }
    // 设置总价钱
    for (var i = 0; i < cart.length; i++) {
      tempPrice += cart[i].value * cart[i].num * 100;
    }
    _that.setData({
      arr: cart,
      totalPrice: tempPrice
    })
  },

  /***
   * 调起导航
   */
  toLocation: function(options) {
    let _that = this;
    let lat = _that.data.lat;
    let lot = _that.data.lot;
    let addr = _that.data.addr;
    let name = _that.data.name;
    wx.openLocation({
      longitude: Number(lot),
      latitude: Number(lat),
      name: name,
      address: addr
    })
  },

  /***
   * 设置步进器变量
   */
  changeStepper: function(options) {
    let _that = this;
    _that.setData({
      stepperValue: options.detail
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})